﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Collections.Specialized;

namespace Alphacat.Model
{
    class BaseService
    {
        /// <summary>
        /// 访问服务器时的cookies
        /// </summary>
        public static CookieContainer CookiesContainer;
        public static string PassTicket = "";
        public static string Skey = "";
        /// <summary>
        /// 向服务器发送get请求  返回服务器回复数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static byte[] SendGetRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "get";

                if (CookiesContainer == null)
                {
                    CookiesContainer = new CookieContainer();
                }

                request.CookieContainer = CookiesContainer;  //启用cookie

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream response_stream = response.GetResponseStream();

                int count = (int)response.ContentLength;
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                return buf;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return null;
            }
        }

        /// <summary>
        /// 向服务器发送get请求  下载请求的文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool downloadGetFile(string url, string path)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "get";

                if (CookiesContainer == null)
                {
                    CookiesContainer = new CookieContainer();
                }

                request.CookieContainer = CookiesContainer;  //启用cookie

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                Stream fileStream = new FileStream(path, FileMode.Create);
                /*
                int count = (int)response.ContentLength;
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                */

                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    fileStream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                fileStream.Close();
                responseStream.Close();
                return true;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return false;
            }
        }
        
        public static string GetModifyDayMonth()
        {
            string[] weekdays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
            string day = weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)];
            string[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
            string month = months[DateTime.Now.Month-1];
            return day + " " + month;
        }
        

        public static string UploadFileWithPath(string filePath, string me, string to)
        {
            string url = "https://file.wx2.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";

            FileInfo fileInfo = new FileInfo(filePath);

            TimeSpan ts = ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string timeStamp = Convert.ToInt64(ts.TotalMilliseconds).ToString();

            string fileMd5 = GetFilePathMd5(filePath);

            string uploadmediarequest = "{" +
                "\"UploadType\": 2," +
                "\"BaseRequest\": {" +
                    "\"Uin\": " + GetCookie("wxuin").Value + "," +
                    "\"Sid\": \"" + GetCookie("wxsid").Value + "\"," +
                    "\"Skey\": \"" + Skey + "\"," +
                    "\"DeviceID\": \"e351853343482297\"" + // 或者尝试一下统一DeviceID
                "}," +
                "\"ClientMediaId\": " + timeStamp + "," +
                "\"TotalLen\": " + fileInfo.Length + "," +
                "\"StartPos\": 0," +
                "\"DataLen\": " + fileInfo.Length + "," +
                "\"MediaType\": 4," +
                "\"FromUserName\": \"" + me + "\"," +
                "\"ToUserName\": \"" + to + "\"," +
                "\"FileMd5\": \"" + fileMd5 + "\"" +
            "}";
            //Console.WriteLine(uploadmediarequest);
            NameValueCollection postBody = new NameValueCollection();
            postBody.Add("id", "WU_FILE_0");
            postBody.Add("name", "code.png");
            postBody.Add("type", "image/png");
            postBody.Add("lastModifiedDate", GetModifyDayMonth() + " " + DateTime.Now.ToString("dd yyyy HH:mm:ss") + " GMT+0800 (中国标准时间)");
            postBody.Add("size", fileInfo.Length.ToString());
            postBody.Add("mediatype", "pic");
            postBody.Add("uploadmediarequest", uploadmediarequest);
            postBody.Add("webwx_data_ticket", GetCookie("webwx_data_ticket").Value);
            postBody.Add("pass_ticket", PassTicket);

            //return FormDataPost(url, "filename", filePath, postBody);

            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close();

            return FormDataUploadCode(url, "filename", bArr, postBody);
        }


        public static string FormDataPost(string url, string fileKeyName,
                                            string filePath, NameValueCollection stringDict)
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            string fileName = filePath.Split('/').Last();
            //Console.WriteLine("filename: " + fileName);

            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            //webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            if (CookiesContainer == null)
            {
                CookiesContainer = new CookieContainer();
            }
            webRequest.CookieContainer = CookiesContainer;

            // 写入文件
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                 "Content-Type: image/png\r\n\r\n"; // 本来是image/png
            var header = string.Format(filePartHeader, fileKeyName, fileName);
            var headerbytes = Encoding.UTF8.GetBytes(header);

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = new byte[1024];
            int bytesRead; // =0

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }

            // 写入字符串的Key
            var stringKeyHeader = "--" + boundary +
                                   "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}\r\n";
            //foreach (string key in stringDict.Keys)
            //{
            //    Console.Write(string.Format(stringKeyHeader, key, stringDict[key]));
            //}
            foreach (byte[] formitembytes in from string key in stringDict.Keys
                                             select string.Format(stringKeyHeader, key, stringDict[key])
                                                 into formitem
                                             select Encoding.UTF8.GetBytes(formitem))
            {
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

            // 写入最后的结束边界符
            memStream.Write(endBoundary, 0, endBoundary.Length);

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();

            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            StreamReader httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                            Encoding.GetEncoding("utf-8"));
            responseContent = httpStreamReader.ReadToEnd();
            // using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), 
            //                                                 Encoding.GetEncoding("utf-8")))
            // {
            //     responseContent = httpStreamReader.ReadToEnd();
            // }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }

        // 目前正在使用
        public static string UploadFileWithBytes(byte[] fileData, string me, string to)
        {
            string url = "https://file.wx2.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";

            //FileInfo fileInfo = new FileInfo(filePath);

            TimeSpan ts = ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string timeStamp = Convert.ToInt64(ts.TotalMilliseconds).ToString();

            //string fileMd5 = GetFilePathMd5(filePath);
            string fileMd5 = GetMD5Hash(fileData);
            string uploadmediarequest = "{" +
                "\"UploadType\": 2," +
                "\"BaseRequest\": {" +
                    "\"Uin\": " + GetCookie("wxuin").Value + "," +
                    "\"Sid\": \"" + GetCookie("wxsid").Value + "\"," +
                    "\"Skey\": \"" + Skey + "\"," +
                    "\"DeviceID\": \"e351853343482297\"" + // 或者尝试一下统一DeviceID
                "}," +
                "\"ClientMediaId\": " + timeStamp + "," +
                "\"TotalLen\": " + fileData.Length + "," +
                "\"StartPos\": 0," +
                "\"DataLen\": " + fileData.Length + "," +
                "\"MediaType\": 4," +
                "\"FromUserName\": \"" + me + "\"," +
                "\"ToUserName\": \"" + to + "\"," +
                "\"FileMd5\": \"" + fileMd5 + "\"" +
            "}";
            //Console.WriteLine(uploadmediarequest);
            NameValueCollection postBody = new NameValueCollection();
            postBody.Add("id", "WU_FILE_0");
            postBody.Add("name", "code.png");
            postBody.Add("type", "image/png");
            postBody.Add("lastModifiedDate", GetModifyDayMonth() + " " + DateTime.Now.ToString("dd yyyy HH:mm:ss") + " GMT+0800 (中国标准时间)");
            postBody.Add("size", fileData.Length.ToString());
            postBody.Add("mediatype", "pic");
            postBody.Add("uploadmediarequest", uploadmediarequest);
            postBody.Add("webwx_data_ticket", GetCookie("webwx_data_ticket").Value);
            postBody.Add("pass_ticket", PassTicket);

            //return FormDataPostByte(url, "filename", fileData, postBody);
            return FormDataUploadCode(url, "filename", fileData, postBody);
        }

        //public static string FormDataPostByte(string url, string fileKeyName,
        //                                    byte[] fileData, NameValueCollection stringDict)
        //{
        //    string responseContent;
        //    var memStream = new MemoryStream();
        //    var webRequest = (HttpWebRequest)WebRequest.Create(url);
        //    // 边界符
        //    var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
        //    // 边界符
        //    var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
        //    //var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        //    //string fileName = filePath.Split('/').Last();
        //    string fileName = "code.png";
        //    //Console.WriteLine("filename: " + fileName);

        //    // 最后的结束符
        //    var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

        //    // 设置属性
        //    webRequest.Method = "POST";
        //    //webRequest.Timeout = timeOut;
        //    webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

        //    if (CookiesContainer == null)
        //    {
        //        CookiesContainer = new CookieContainer();
        //    }
        //    webRequest.CookieContainer = CookiesContainer;

        //    // 写入文件
        //    const string filePartHeader =
        //        "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
        //         "Content-Type: image/png\r\n\r\n"; // 本来是image/png
        //    var header = string.Format(filePartHeader, fileKeyName, fileName);
        //    var headerbytes = Encoding.UTF8.GetBytes(header);

        //    memStream.Write(beginBoundary, 0, beginBoundary.Length);
        //    memStream.Write(headerbytes, 0, headerbytes.Length);

        //    //var buffer = new byte[1024];
        //    //int bytesRead; // =0

        //    //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        //    //{
        //    //    memStream.Write(buffer, 0, bytesRead);
        //    //}
        //    memStream.Write(fileData, 0, fileData.Length);

        //    // 写入字符串的Key
        //    var stringKeyHeader = "--" + boundary +
        //                           "\r\nContent-Disposition: form-data; name=\"{0}\"" +
        //                           "\r\n\r\n{1}\r\n";
        //    //foreach (string key in stringDict.Keys)
        //    //{
        //    //    Console.Write(string.Format(stringKeyHeader, key, stringDict[key]));
        //    //}
        //    foreach (byte[] formitembytes in from string key in stringDict.Keys
        //                                     select string.Format(stringKeyHeader, key, stringDict[key])
        //                                         into formitem
        //                                     select Encoding.UTF8.GetBytes(formitem))
        //    {
        //        memStream.Write(formitembytes, 0, formitembytes.Length);
        //    }

        //    // 写入最后的结束边界符
        //    memStream.Write(endBoundary, 0, endBoundary.Length);

        //    webRequest.ContentLength = memStream.Length;

        //    var requestStream = webRequest.GetRequestStream();

        //    memStream.Position = 0;
        //    var tempBuffer = new byte[memStream.Length];
        //    memStream.Read(tempBuffer, 0, tempBuffer.Length);
        //    memStream.Close();

        //    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        //    requestStream.Close();

        //    var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

        //    StreamReader httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
        //                                                    Encoding.GetEncoding("utf-8"));
        //    responseContent = httpStreamReader.ReadToEnd();
        //    // using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), 
        //    //                                                 Encoding.GetEncoding("utf-8")))
        //    // {
        //    //     responseContent = httpStreamReader.ReadToEnd();
        //    // }

        //    //fileStream.Close();
        //    httpWebResponse.Close();
        //    webRequest.Abort();

        //    return responseContent;
        //}

        public static string UploadServer(string filePath)
        {
            try
            {
                string url = "http://www.aimiaoyin.com/print/terminal.php?m=admin&c=file&a=upload";
                
                //string url = "http://hcdstudio.cn/files/upload_file.php";
                return HttpUploadFile(url, filePath);

                //return FormDataPost(url, "file", filePath, null);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return null;
            }
        }

        // 目前正在使用
        public static string UploadServerWithBytes(byte[] fileData, string fileName)
        {
            try
            {
                string url = "http://www.aimiaoyin.com/print/terminal.php?m=admin&c=file&a=upload";

                //string url = "http://hcdstudio.cn/files/upload_file.php";
                return HttpUploadFileBytes(url, fileData, fileName);
                

                //return FormDataPost(url, "file", filePath, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return null;
            }
        }

        /// <summary>
        /// Http上传文件
        /// </summary>
        public static string HttpUploadFile(string url, string path)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
            int pos = path.LastIndexOf("\\");
            string fileName = path.Substring(pos + 1);
            //请求头部信息 
            StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"printFile\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close();
            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(bArr, 0, bArr.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            //返回结果网页（html）代码
            string content = sr.ReadToEnd();
            return content;
        }

        // 目前正在使用
        public static string HttpUploadFileBytes(string url, byte[] fileData, string fileName)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
            //int pos = path.LastIndexOf("\\");
            //string fileName = path.Substring(pos + 1);
            //请求头部信息 
            StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"printFile\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
            //FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            //byte[] bArr = new byte[fs.Length];
            //fs.Read(bArr, 0, bArr.Length);
            //fs.Close();
            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(fileData, 0, fileData.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            //返回结果网页（html）代码
            string content = sr.ReadToEnd();
            return content;
        }

        // 目前正在使用
        public static string FormDataUploadCode(string url, string fileKeyName, byte[] fileData, NameValueCollection stringDict)
        {
            try
            {
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = CookiesContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                //int pos = path.LastIndexOf("\\");
                string fileName = "code.png"; //path.Substring(pos + 1);


                //请求头部信息 
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileKeyName, fileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                //FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                //byte[] bArr = new byte[fs.Length];
                //fs.Read(bArr, 0, bArr.Length);
                //fs.Close();

                Stream postStream = request.GetRequestStream();

                // 写入字符串的Key
                var stringKeyHeader = "--" + boundary +
                                       "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                       "\r\n\r\n{1}\r\n";
                foreach (string key in stringDict.Keys)
                {
                    string postParam = string.Format(stringKeyHeader, key, stringDict[key]);
                    //Console.Write(postParam);
                    byte[] paramBytes = Encoding.UTF8.GetBytes(postParam);
                    postStream.Write(paramBytes, 0, paramBytes.Length);
                }

                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                postStream.Write(fileData, 0, fileData.Length);
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                postStream.Close();
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                return content;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return null;
            }
            
        }
        

        public static string GetMD5Hash(byte[] bytedata)
        {
            try
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(bytedata);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5Hash() fail,error:" + ex.Message);
            }
        }

        public static string GetFilePathMd5(string filePath)
        {
            try
            {
                FileStream file = new FileStream(filePath, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail, error:" +ex.Message);
            }
        }

        /// <summary>
        /// 向服务器发送post请求 返回服务器回复数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static byte[] SendPostRequest(string url, string body, string type)
        {
            if (type == null || type == "")
            {
                type = "application/x-www-form-urlencoded";
            }
            type += ";charset=UTF-8";
            try
            {
                byte[] request_body = Encoding.UTF8.GetBytes(body);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "post";
                request.ContentLength = request_body.Length;
                request.ContentType = type;
                Stream request_stream = request.GetRequestStream();

                request_stream.Write(request_body, 0, request_body.Length);

                if (CookiesContainer == null)
                {
                    CookiesContainer = new CookieContainer();
                }
                request.CookieContainer = CookiesContainer;  //启用cookie

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream response_stream = response.GetResponseStream();

                int count = (int)response.ContentLength;
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                return buf;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return null;
            }
        }
        /// <summary>
        /// 获取指定cookie
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Cookie GetCookie(string name)
        {
            List<Cookie> cookies = GetAllCookies(CookiesContainer);
            foreach (Cookie c in cookies)
            {
                if (c.Name == name)
                {
                    return c;
                }
            }
            return null;
        }

        private static List<Cookie> GetAllCookies(CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();

            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
                System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                    | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies) lstCookies.Add(c);
            }
            return lstCookies;
        }
    }
}
